#-*- coding:utf-8 -*-
'''
Created on Oct 22, 2012

@author: johnny
'''
from utils import configer
from db import db_connector

class TestDB(object):
    def __init__(self, host="localhost"):
        self.db = db_connector.DataBaseConnection()
        
        self.configer = configer.Configer()
        self.configer.set_config_file()
        self.configer.parse_config_file()
        
        self.db_type = 'mysql'
        self.host = host
        self.user = self.configer.get_config_value('database', 'user')
        self.passwd = \
        self.configer.get_config_value('database', 'password')
        self.db_name = \
        self.configer.get_config_value('database', 'databasename')
        self.retry_times = 10     
        
    def query(self, table, keyword=None, column='*'):
        if keyword: 
            command = ('SELECT ' + column + ' from ' + table +
                       ' ' + keyword)
        else:
            command = 'SELECT ' + column + ' from ' + table
            
        command = command + ';'
        
        return self.execute(command)
    
    def insert(self, table, dct):
        keys = tuple(dct.keys())
        values = tuple([dct[x] for x in keys])
        
        raw_key = str(keys).replace("\'", '')
        
        command = ("INSERT INTO %s %s VALUES" %
                   (str(table), raw_key))
        
        command += "(%s, %s, %s, %s, %s, %s, %s, %s);"
        return self.execute(command, values)
    
    def insert1(self, table, value):
        command = ("INSERT INTO %s %s VALUES" %
                  (str(table), "(uid, test_name, status)"))
        command += "(%s, %s, %s);"
        return self.execute(command, value)

    def execute(self, command, parameters=None):
        self.db.connect(self.db_type, self.host, 3306,
                               self.user, self.passwd, self.db_name)
        result = self.db.execute(command, parameters)
        self.db.disconnect()
        return result
    
    def get_max_id(self):
        column = 'max(id)'
        results = self.query('test_cases', column=column)
        if results:
            arr = [x[0] for x in results]
            if len(arr):
                return arr[0]
        else:
            return 0
        
    def update_column(self, key, val='', table='progress', 
                      condition='where id=1'):
        command = ("""update %s set %s='%s' %s;""" %
                   (table, key, val, condition))
        if self.query(table, condition, "*"):
            return self.execute(command)
        
    def update_progress(self, status, progress):
        self.update_column('status', status)
        self.update_column('progress', progress)
        
    def delete_all(self, table="current_tests"):
        command = """delete from %s""" % table
        
        return self.execute(command)
        
        